﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using JQuery.WebKit.Base;
using JQuery.WebKit.WebCommon;

namespace JQuery.WebKit
{
    //[Designer("System.Web.UI.Design.WebControls.PanelContainerDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
    [ParseChildren(typeof(JMenuItem), DefaultProperty = "MenuItems", ChildrenAsProperties = true)]
    [ToolboxData("<{0}:MenuItem runat=\"server\"></{0}:MenuItem>")]
    public class JMenuItem : WebControlBase, INamingContainer, ITemplate
    {
        private int _index;
        private int _level;

        public JMenu Menu
        {
            get;
            private set;
        }

        [PersistenceMode(PersistenceMode.InnerProperty),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<JMenuItem> MenuItems
        {
            get;
            private set;
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        Browsable(false),
        EditorBrowsable(EditorBrowsableState.Never)]
        public override string CssClass
        {
            get
            {
                return base.CssClass;
            }
            set
            {
                base.CssClass = value;
            }
        }

        public string Text
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        [UrlProperty("*.aspx")]
        public string Url
        {
            get;
            set;
        }

        public JMenuItem()
            : base(HtmlTextWriterTag.Li)
        {
            MenuItems = new List<JMenuItem>();
        }

        public void InstantiateIn(Control container)
        {
            JPage page = container.FindParent<JPage>();
            if (page == null)
            {
                return;
            }
            //if (page.Authentication == null || (!string.IsNullOrEmpty(Name) && !page.Authentication.CheckName(Name)))
            //{
            //    return;
            //}
            _index = container.Controls.Count;
            container.Controls.Add(this);

            if (container is JMenuItem)
            {
                _level = (container as JMenuItem)._level + 1;
            }

            Menu = this.FindParent<JMenu>();
        }

        protected override void CreateChildControls()
        {
            MenuItems.ForEach(item => item.InstantiateIn(this));
        }

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            base.CssClass = string.Format("menuItemContainer_{0} {1}", _level, this.ID);
            base.RenderBeginTag(writer);
            StringBuilder sb = new StringBuilder();

            bool isDefault = string.IsNullOrEmpty(Url) ? false : Page.Request.Url.AbsolutePath.ToLower().EndsWith(Url.ToLower());
            if (this.Controls.Count > 0 || this.Parent is JMenu)
            {
                sb.AppendFormat("<a href=\"{0}\" class='menuItemContainerRef {1}_{2}'>", string.IsNullOrEmpty(Url) ? "#" : Page.ResolveClientUrl(Url), Parent.ID, _index);
            }
            else
            {
                sb.AppendFormat("<a href=\"{0}\" class='menuItemRef {1}{2}'>", string.IsNullOrEmpty(Url) ? "#" : Page.ResolveClientUrl(Url), this.ID, isDefault ? " default" : "");
            }

            if (!string.IsNullOrEmpty(Text))
            {
                sb.AppendFormat("<span>{0}</span>", Text);
            }

            sb.Append("</a>");

            if (this.Controls.Count > 0)
            {
                if (this.Parent is JMenu)
                {
                    sb.AppendFormat("<ul id='{0}_Container' class='menuContainer' style='display:none'>", this.ID);
                }
                else
                {
                    sb.AppendFormat("<ul id='{0}_Container' class='menuContainer'>", this.ID);
                }
            }
            
            writer.Write(sb.ToString());
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
            if (this.Controls.Count > 0)
            {
                writer.Write("</ul>");
            }
            base.RenderEndTag(writer);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (this.Controls.Count == 0 && string.IsNullOrEmpty(Url))
            {
                return;
            }
            base.Render(writer);
        }
    }
}
